package com.csj.mvvm.utils;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;

import com.csj.mvvm.App;
import com.csj.mvvm.R;


/**
 * 对话框提示
 */
public class CustomDialog {

    /**
     * 视图构建器
     */
    public static class Builder {

        private Dialog dialog;
        private Context mContext;
        private View mDialogView;
        private LinearLayout mMainLl;
        private LinearLayout mContentLl;
        private TextView sure;
        private TextView cancel;
        private TextView title;
        //确定按钮不取消对话框，回调方法dialog自己取消
        private OnClickListener mPositiveButtonListener;
        private OnClickListener mNegativeButtonListener;
        private boolean mCancelable = true;
        private OnCancelListener mOnCancelListener;

        public Builder(Context context) {
            mContext = context;
            mDialogView = DataBindingUtil.inflate(
                    LayoutInflater.from(App.instance),
                    R.layout.dialog_full,
                    null,
                    false
            ).getRoot();
            mMainLl = mDialogView.findViewById(R.id.mainDlg);
            mContentLl = mDialogView.findViewById(R.id.ll);
            mContentLl.setOnClickListener(v -> {
            });//点击Dialog不消失
        }

        /**
         * 设置布局位置
         *
         * @return
         */
        public Builder setGravity(int gravity) {
            mMainLl.setGravity(gravity);
            return this;
        }

        /**
         * 设置自定义内容的显示
         *
         * @return
         */
        public Builder setView() {
            setWrapLp();
            View view = DataBindingUtil.inflate(
                    LayoutInflater.from(App.instance),
                    R.layout.dialog_content_del,
                    null,
                    false
            ).getRoot();
            sure = view.findViewById(R.id.sure);
            cancel = view.findViewById(R.id.cancel);
            title = view.findViewById(R.id.title);
            mContentLl.addView(view);
            return this;
        }

        public Builder setView(String msg) {
            setWrapLp();
            View view = DataBindingUtil.inflate(
                    LayoutInflater.from(App.instance),
                    R.layout.dialog_content_del,
                    null,
                    false
            ).getRoot();
            sure = view.findViewById(R.id.sure);
            cancel = view.findViewById(R.id.cancel);
            title = view.findViewById(R.id.title);
            title.setText(msg + "");
            view.findViewById(R.id.line).setVisibility(View.GONE);
            cancel.setVisibility(View.GONE);
            sure.setBackground(mContext.getResources().getDrawable(R.drawable.shape_dialog_bottom));
            mContentLl.addView(view);
            return this;
        }

        /**
         * 设置标题文本
         *
         * @param msg
         * @return
         */
        public Builder setMessage(CharSequence msg) {
            title.setText(msg);
            return this;
        }

        /**
         * 设置自定义内容的显示
         * 布局宽度默认android:layout_width="match_parent"
         * 如果要设定成固定宽度需要
         * 1.使用setWrapLp()方法
         * 2.xml的子布局设定固定宽度（母布局设置无效）
         * 参考R.layout.dialog_content_del
         *
         * @param view
         * @return
         */
        public Builder setView(View view) {
            if (view.getParent() != null) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
            mContentLl.addView(view);
            return this;
        }

        /**
         * 设置自定义View的标题和确定、取消 按钮
         *
         * @param view
         * @return
         */
        public Builder setViewBtn(View view) {
            sure = view.findViewById(R.id.sure);
            cancel = view.findViewById(R.id.cancel);
            title = view.findViewById(R.id.title);
            return this;
        }

        public Builder setWrapLp() {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mContentLl.setLayoutParams(lp);
            return this;
        }

        /**
         * 设置一个确认按钮
         *
         * @param textId
         * @param listener
         * @return
         */
        public Builder setPositiveButton(int textId, final OnClickListener listener) {
            return setPositiveButton(mContext.getResources().getString(textId), listener);
        }

        public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
            mPositiveButtonListener = listener;
            sure.setText(text);
            return this;
        }

        public Builder setPositiveButton(final OnClickListener listener) {
            mPositiveButtonListener = listener;
            return this;
        }

        /**
         * 设置一个否定按钮
         *
         * @param textId
         * @param listener
         * @return
         */
        public Builder setNegativeButton(int textId, final OnClickListener listener) {
            return setNegativeButton(mContext.getString(textId), listener);
        }

        public Builder setNegativeButton(CharSequence text, final OnClickListener listener) {
            mNegativeButtonListener = listener;
            sure.setText(text);
            return this;
        }

        public Builder setNegativeButton(final OnClickListener listener) {
            mNegativeButtonListener = listener;
            return this;
        }

        /**
         * 设置是否可以取消 默认为true
         *
         * @param cancelable
         * @return
         */
        public Builder setCancelable(boolean cancelable) {
            mCancelable = cancelable;
            return this;
        }

        /**
         * 设置Dialog取消回调
         *
         * @param onCancelListener
         * @return
         */
        public Builder setOnCancelListener(OnCancelListener onCancelListener) {
            mOnCancelListener = onCancelListener;
            return this;
        }

        /**
         * 创建一个Dialog
         */
        public Dialog create() {
            dialog = new Dialog(mContext, R.style.CustomDialogStyle);
            dialog.setContentView(mDialogView);
            dialog.setCancelable(mCancelable);
            dialog.setCanceledOnTouchOutside(mCancelable);
            //全屏
            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, getHeight() - getStatusBarHeight());
            if (mCancelable) {
                mDialogView.findViewById(R.id.mainDlg).setOnClickListener(v -> {
                    dialog.cancel();
                });
            }
            dialog.setOnCancelListener(mOnCancelListener);
            if (sure != null) {
                //确定按钮不取消对话框，回调方法dialog自己取消
                sure.setOnClickListener(v -> {
                    if (mPositiveButtonListener != null) {
                        mPositiveButtonListener.onClick(dialog, 0);
                    }
                });
            }
            if (cancel != null) {
                cancel.setOnClickListener(v -> {
                    dialog.dismiss();
                    if (mNegativeButtonListener != null) {
                        mNegativeButtonListener.onClick(dialog, 0);
                    }
                });
            }

            return dialog;
        }

        /**
         * 显示该视图
         *
         * @return
         */
        public Builder show() {
            create().show();
            return this;
        }


        /**
         * 弹出一个加载中的对话框
         */
        public Dialog createLoading(String msg) {
            dialog = new Dialog(mContext, R.style.CustomDialogStyle);
            dialog.setContentView(mDialogView);
            dialog.setCancelable(mCancelable);
            dialog.setCanceledOnTouchOutside(mCancelable);
            //全屏
            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, getHeight() - getStatusBarHeight());

            View vv = DataBindingUtil.inflate(
                    LayoutInflater.from(App.instance),
                    R.layout.loading_dialog2,
                    null,
                    false
            ).getRoot();// 得到加载view
            // main.xml中的ImageView
            spaceshipImage = vv.findViewById(R.id.img);
            TextView tipTextView = vv.findViewById(R.id.tipTextView);// 提示文字
            tipTextView.setText(msg);// 设置加载信息
            mContentLl.addView(vv);
            if (mCancelable) {
                vv.findViewById(R.id.dialog_view).setOnClickListener(v -> {
                    dialog.cancel();
                });
                mDialogView.findViewById(R.id.mainDlg).setOnClickListener(v -> {
                    dialog.cancel();
                });
            }
            return dialog;
        }

        private ImageView spaceshipImage;
        private Animation animation;

        public void startAnimation() {
            if (spaceshipImage != null && spaceshipImage.getAnimation() == null) {
                // 加载动画
                if (animation == null) {
                    animation = AnimationUtils.loadAnimation(mContext, R.anim.loading_animation);
                }
                // 使用ImageView显示动画
                spaceshipImage.startAnimation(animation);
            }
        }

    }

    public static int getHeight() {
        WindowManager wm = (WindowManager) App.instance.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获取状态栏高度
     *
     * @return 状态栏高度
     */
    public static int getStatusBarHeight() {
        int result = 0;
        int resourceId = App.instance.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = App.instance.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
